import redirect


from mainapp.models import Network, NetworkCredential
import py_social

#Example API usage - very rough right now.
#TODO: cleanup and document API usage
class Handler(object):

    def register(self, request):
        #Get the network object from the DB
        network = Network.objects.get(name = request.GET.get('network'))

        #get a py_social network object from the db object
        network = py_social.NetworkFactory(network)

        return redirect(network.get_auth_url())

    def callback(self, request, network):

        #Get the network object from the DB
        network = Network.objects.get(name=network)

        #get a py_social network object from the db object
        network = py_social.NetworkFactory(network)

        #generate a credential from the request object's code
        cred = network.new_credential(code=request.GET.get('code'))

        #Save the credential to the DB for later use
        NetworkCredential.objects.create(**cred.toDict())

    def checkin(self, request, network, user):

        #Get the network object from the DB
        network = Network.objects.get(name=network)

        #get a py_social network object from the db object
        network = py_social.NetworkFactory(network)

        #get a user credential from the DB
        cred = NetworkCredential.objects.get(network=network.name, user=user)

        #get a py_social credential object from the db credential object
        cred = network.load_credential(cred)

        #checkin the credential on that network
        network.checkin(cred, lng=50, lat=40)

